<template>
  <div>
    <vxe-toolbar custom  ref="toolbarRef" >
      <template #buttons>
        <el-button
                type="primary"
                icon="el-icon-plus"
                @click="handleAdd"
                v-if="this.editable"
        >
          新 增
        </el-button>
      </template>
      <template #tools>

        <el-tooltip content="清空筛选" placement="top">
          <vxe-button  icon="vxe-icon-delete" class="tool-btn" @click="$refs.tableRef.clearFilter()" circle></vxe-button>
        </el-tooltip>

        <vxe-button  icon="vxe-icon-refresh" class="tool-btn" @click="refresh" circle style="margin-right: 12px;"></vxe-button>
      </template>
    </vxe-toolbar>
    <vxe-grid
            v-bind="gridOptions"
            id="tableRef"
            ref="tableRef"
            show-footer
            class="mytable-scrollbar"
            :data="list"
            :edit-rules="validRules"
            :tooltip-config="{ zIndex: 9999 }"
            :customConfig="customConfig"
            :menu-config="menuConfig"
            :footer-method="footerMethod"
            :edit-config="{
                trigger: 'click',
                mode: 'row',
                showUpdateStatus: true,
                showInsertStatus: true,
                beforeEditMethod:beforeEdit}"
            @edit-closed="editClosedEvent"
            @edit-actived="editActivedEvent"
    >
      <!--<vxe-column type="checkbox" width="50"></vxe-column>-->
      <template #unit_edit="scope">
        <el-select v-model="scope.row.unit" type="text" clearable transfer filterable>
          <el-option
                  v-for="item in unitList"
                  :key="item.name"
                  :value="item.name"
                  :label="item.name"/>
        </el-select>
      </template>

      <template #price_edit="scope">
        <vxe-input v-model="scope.row.price" type="float" digits="3" max="99999999" @change="(value)=>calTotalPrice(value.value, scope.row.num, scope)"></vxe-input>
      </template>


      <template #customPrice_edit="{ row }">
        <vxe-input v-model="row.customPrice" type="float" digits="3" max="99999999"></vxe-input>
      </template>

      <template #num_edit="scope">
        <vxe-input v-model="scope.row.num" type="integer" min="0" max="99999999"  @change="(value)=>calTotalPrice(scope.row.price,value.value,scope, 1)"
        @blur="(value)=>changeAbc(value.value,scope.row)"></vxe-input>
      </template>

      <template #deliDate_default="{ row }">
        {{ row.deliDate}}
      </template>
      <template #deliDate_edit="scope">
        <el-date-picker v-model="scope.row.deliDate" type="date" transfer format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" ></el-date-picker>
      </template>

      <template #packLabelName_default="{ row }">
        {{ row.packLabelName}}
      </template>
      <template #packLabelName_edit="scope">
        <el-select v-model="scope.row.packLabelName" type="text" @change="handlePackLabelContent(scope.row)" clearable transfer>
          <el-option
          v-for="item in packLabelNameList"
          :key="item"
          :value="item"
          :label="item"/>
        </el-select>
      </template>

      <template #btn_default="{ row }">
        <template v-if="!isActiveStatus(row) && this.editable">
          <!--<el-tooltip content="修改" placement="top">-->
          <!--<el-button-->
          <!--size="small"-->
          <!--type="primary"-->
          <!--@click="handleUpdate(row)"-->
          <!--&gt;修改-->
          <!--</el-button>-->
          <!--</el-tooltip>-->
          <el-tooltip content="删除" placement="top">
            <el-button
                    icon="el-icon-delete"
                    link
                    size="small"
                    type="primary"
                    @click="handleDelete(row)"
            ></el-button>
          </el-tooltip>
        </template>
      </template>
    </vxe-grid>

    <!--<div style="margin-top:20px">-->
    <!--<vxe-pager -->
    <!--v-model:current-page="page.currentPage" -->
    <!--v-model:page-size="page.pageSize" -->
    <!--:total="page.total"-->
    <!--@page-change='pageChange'-->
    <!--background-->
    <!--:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes',  'Total']"-->
    <!--size="small" -->
    <!--/>-->
    <!--</div>-->
    <select-prod  ref="selectProd" @success="setMaterial" />
  </div>
</template>

<script>
    import {getList, getDetail, add, update, remove,findList} from "@/api/anwise/order/order_item";
    import {checkProd} from "@/api/anwise/order/order";
    import {select as unitSelect} from "@/api/anwise/unit_info";

    import {mapGetters} from "vuex";
    import {VXETable} from 'vxe-table'
    import {getDictionary} from "@/api/system/dictbiz"
    import {select} from "@/api/base/region";
    import {Pattern} from "@/utils/validate.js";
    import {dateFormat} from "@/utils/date.js";
    import selectProd from './select_prod.vue';
    export default {
        components: {
            selectProd
        },
        data() {
            return {
                unitList:[],
                yesNoList:[],
                packLabelNameList:["标准箱唛","特殊箱唛"],
                customerId:'',
                salesDate:'',
                bankId:'',
                idNo:undefined,
                searchShow:false,
                editable:true,
                props: {
                    customerId: {
                        type: String,
                        default: ""
                    },
                    salesDate: {
                      type: String,
                      default: ""
                    },
                },
                list: [],
                customConfig: {
                    storage: true,
                    checkMethod({column}) {
                        if (['materialNo'].includes(column.field)) {
                            return false
                        }
                        if (['idNo'].includes(column.field)) {
                            return false
                        }
                        if (['itemNo'].includes(column.field)) {
                            return false
                        }
                        return true
                    },
                },
                menuConfig: {},
                form: {},
                query: {},
                loading: true,
                data: [],
                selectionList: [],
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                subVisible: false,
                direction: 'rtl',
                customerName: "安伟客户表",
                customerTypeList: [],
                nameOptions: [{data: null}],
                validRules: {
                    price: [
                        {required: true, message: '单价/100PCS必须填写'}
                    ],
                    num: [
                        {required: true, message: '数量必须填写'}
                    ],
                  unit:[
                    {required: true, message: '单位必须填写'}
                  ]
                    // contact: [
                    //     {required: true, message: '联系人必须填写'}
                    // ],
                    // contactPhone: [
                    //     {required: true, message: '联系电话必须填写'}
                    // ],
                    // contactEmail: [
                    //     {required: false,pattern: Pattern.email, message: '邮件格式错误'}
                    // ]
                },
                gridOptions: {
                  height: '400px',
                  border: true,
                  showOverflow: true,
                  keepSource: true,
                  size: "medium",
                  rowConfig: {
                    // keyField: 'id',
                    isHover: true
                  },
                  columnConfig: {
                    resizable: true
                  },
                  // editRules: ,
                  columns: [
                    // {type: 'checkbox', width: 50, fixed:'left', visible: true},
                    // {type: 'seq', width: 50, fixed:'left', align: "center"},
                    {
                      title: "订单编号",
                      field: "idNo",
                      minWidth: 160,
                    },
                    {
                      title: "订单项",
                      field: "itemNo",
                      minWidth: 80,
                    },
                    {
                      title: "物料编号",
                      field: "materialNo",
                      minWidth: 160,
                      filters: [{ data: '' }],
                      filterRender: { name: 'FilterInput'}
                    },
                    {
                      title: "物料名称",
                      field: "materialName",
                      minWidth: 160,
                      filters: [{ data: '' }],
                      filterRender: { name: 'FilterInput'}
                    },
                    {
                      title: "客户条码",
                      field: "barCode",
                      minWidth: 160,
                      fixed: 'left',
                      filters: [{ data: '' }],
                      filterRender: { name: 'FilterInput'}
                    },
                    {
                      title: "产品描述",
                      field: "materialDesc",
                      minWidth: 200,
                        editRender:{ name:'EditDownTextarea',maxlength:2000,props:{maxlength:2000,rows:5,showWordCount:true}},
                    },
                    {
                      title: "单位",
                      field: "unit",
                        minWidth: 100,
                      editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                      slots: {edit: 'unit_edit'}
                    },
                    {
                      title: "单价/100PCS",
                      field: "price",
                        minWidth: 200,
                      editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                      slots: {edit: 'price_edit'}
                    },
                    {
                      title: "清关单价",
                      field: "customPrice",
                        minWidth: 160,
                      editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                      slots: {edit: 'customPrice_edit'}
                    },
                    {
                      title: "数量",
                      field: "num",
                        minWidth: 120,
                      editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                      slots: {edit: 'num_edit'}
                    },
                    {
                      title: "金额",
                      field: "totalPrice",
                        minWidth: 120,
                      editRender:{ autofocus: '.vxe-input--inner' , enabled: false, events: {change: this.updateFooterEvent} }
                      // slots: {edit: 'postcode_edit', default: 'postcode_default'}
                    },
                    {
                      title: "预交日期",
                      field: "deliDate",
                        minWidth: 160,
                      editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                      slots: {edit: 'deliDate_edit', default: 'deliDate_default'}
                    },
                    {
                      title: "箱唛名称",
                      field: "packLabelName",
                        minWidth: 120,
                      editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                      slots: {edit: 'packLabelName_edit', default: 'packLabelName_default'}
                    },
                    {
                      title: "箱唛内容",
                      field: "packLabelContent",
                        minWidth: 300,
                        editRender:{ name:'EditDownTextarea',maxlength:2000,props:{maxlength:2000,rows:5,showWordCount:true}},
                    },
                    {
                      title: "备注",
                      field: "remark",
                        minWidth: 300,
                      editRender:{ name:'EditDownTextarea',maxlength:2000,props:{maxlength:2000,rows:5,showWordCount:true}},
                      // slots: {edit: 'remark_edit', default: 'remark_default'}
                    },
                    {
                      title: "已排产数量",
                      field: "prodNum",
                        minWidth: 120,
                    },
                    {
                      title: "排产已完成",
                      field: "prodComplete",
                        minWidth: 120,
                    },
                    {
                      title: "已入仓数量",
                      field: "stockNum",
                        minWidth: 120,
                    },
                    {
                      title: "入仓已完成",
                      field: "stockComplete",
                        minWidth: 120,
                    },
                    {
                      title: "已送货数量",
                      field: "deliNum",
                        minWidth: 120,
                    },
                    {
                      title: "送货已完成",
                      field: "deliComplete",
                        minWidth: 120,
                    },
                    {
                      title: "仓存数量",
                      field: "totalStockNum",
                        minWidth: 120,
                    },
                    {
                      title: "件数",
                      field: "pcsCount",
                        minWidth: 120,
                    },
                    {
                      title: "方数",
                      field: "cubeNum",
                        minWidth: 120,
                    },
                    {
                      title: "品牌",
                      field: "programName",
                      minWidth: 120,
                    },
                    {
                      field: 'btn',
                      title: '操作',
                      minWidth: 120,
                      align: "center",
                      fixed: "right",
                      visible: true,
                      slots: {default: 'btn_default'}
                    }
                  ]
                },
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.customer_add, false),
                    viewBtn: this.validData(this.permission.customer_view, false),
                    delBtn: this.validData(this.permission.customer_delete, false),
                    editBtn: this.validData(this.permission.customer_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            },
            subIds() {
                let ids = [];
                this.selectionListSub.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
            this.initDict();
            this.menuConfig = {
                header: {
                    options: [
                        [
                            {code: 'hideColumn', name: '隐藏列', disabled: false},
                            {code: 'showAllColumn', name: '取消所有隐藏列', disabled: false},
                        ],
                    ],
                },
                body: {
                    options: [
                        [
                            {
                                code: 'copy',
                                name: '复制',
                                prefixIcon: 'vxe-icon-copy',
                                disabled: false,
                            },
                        ],
                    ],
                },
                visibleMethod({options, column}) {
                    const isDisabled = !column
                    options.forEach((list) => {
                        list.forEach((item) => {
                            item.disabled = isDisabled
                        })
                    })
                    return true
                },
            }
            this.$nextTick(() => {
                console.log(this.$refs.tableRef)
                console.log(this.$refs.toolbarRef)
                this.$refs.tableRef.connect(this.$refs.toolbarRef);
            })
        },
        methods: {
            handlePackLabelContent(row){
              if(row.packLabelName === "标准箱唛"){
                row.packLabelContent = row.packLabel;
              }else if(row.packLabelName === "特殊箱唛"){
                row.packLabelContent = row.packLabel2;
              }
            },
            changeAbc(value,row) {
                console.log(row);
                // if (Number(row.num) < Number(row.prodNum) && !this.permission.order_super) {
                //     console.log("订单数量不能小于已排产数量")
                //     row.num = row.prodNum;
                //     this.$message.warning("订单数量不能小于已排产数量！")
                //     // return;
                //   // this.$message.warning("已排产！")
                // } else
                  if (Number(row.num) < Number(row.deliNum)) {
                    console.log("订单数量不能小于已送货数量")
                    row.num = row.deliNum;
                    this.$message.warning("订单数量不能小于已送货数量！")
                    // return;
                }
                else if (row.fullBox=='是'&& row.maxNum && Number(row.maxNum) > 0 && row.num) {
                    if (row.num%row.maxNum > 0) {
                        console.log("此产品需要整箱订购")
                        // console.log("row.num%row.maxNum",row.num%row.maxNum);
                        // console.log("row",row);
                        // console.log("Number(row.maxNum-(row.num%row.maxNum))",Number(row.maxNum-(row.num%row.maxNum)))
                        // console.log("Number(row.num)",Number(row.num));
                        row.num = Number(row.num) + Number(row.maxNum-(row.num%row.maxNum));
                        // row.num = 123;
                        // console.log("Number(row.num) + Number(row.maxNum-(row.num%row.maxNum))",Number(row.num) + Number(row.maxNum-(row.num%row.maxNum)));
                        this.$message.warning("此产品需要整箱订购，系统已自动更正数量，请注意!")
                        // return;
                    }
                }
                if (row.num && row.price) {
                    row.totalPrice = this.$toFixed(row.price/100*row.num,2);
                }
                if (row.maxNum && row.maxNum> 0) {
                    row.pcsCount = Math.ceil(this.$toFixed(row.num/row.maxNum,3));
                    if (row.packSize ) {
                        row.cubeNum = this.$toFixed(Math.ceil(row.num/row.maxNum) * row.packSize,2);
                    }
                }
                this.updateFooterEvent();
            },
            calTotalPrice(price, num, scope, type) {
              this.$refs.tableRef.updateStatus(scope);
              let row = scope.row;
              if (num && price) {
                  row.totalPrice = this.$toFixed(price/100*num,2);
              }
              if (type === 1 && row.maxNum && row.maxNum> 0) {
                  row.pcsCount = Math.ceil(this.$toFixed(num/row.maxNum,3));
                  if (row.packSize ) {
                      row.cubeNum = this.$toFixed(Math.ceil(num/row.maxNum) * row.packSize,2);
                  }
              }
            },
            refresh(){
                this.page = {
                    pageSize: 10,
                    currentPage: 1,
                }
                this.query = {}
                this.query.idNo = this.idNo
                this.onLoad(this.page)
            },
            pageChange(e){
                this.page = {
                    pageSize: e.pageSize,
                    currentPage: e.currentPage,
                }
                this.onLoad(this.page)
            },
            beforeEdit({ row, rowIndex, column, columnIndex }) {
                console.log('column',column);
                if (this.editable) {
                    if (column.field == 'materialDesc') {
                        if (row.materialNo.startsWith('PHCOST')) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
                return this.editable;
            },

            isActiveStatus(row) {
                const $table = this.$refs.tableRef
                if ($table) {
                    return $table.isEditByRow(row)
                }
            },
            handleAdd() {
                if (!this.customerId) {
                    this.$message({
                        type: "error",
                        message: "请先选择客户账号！"
                    });
                    return;
                }
                if (!this.bankId) {
                    this.$message({
                        type: "error",
                        message: "请先选择收款方！"
                    });
                    return;
                }
                // let selectList = [];
                // this.list.forEach(item => {
                //     selectList.push({
                //         id: item.materialId,
                //         materialNo: item.materialNo,
                //         materialName: item.materialName,
                //     });
                // })
              console.log(this.salesDate)
              this.$refs.selectProd.showSelect(this.$refs.tableRef.getTableData().fullData, this.customerId, this.bankId,this.salesDate);
            },
            async setMaterial(list) {
                const $table = this.$refs.tableRef

                if (list.length > 0) {
                  this.$emit("disabledFiled", true);
                }
                let $this = this;
                if (!$table.getEditRecord()) {
                    if ($table) {
                        let deliDate = new Date();
                        deliDate.setDate(deliDate.getDate()+14);
                        list.forEach(await function(item) {
                          // const item = list[i];
                          // if (!$table.getTableData().fullData.some((val) =>(val.materialNo == item.materialNo))) {
                          const isComplete = item.materialNo.includes("PHCOST");
                          let maxNo = 0;
                          if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                            maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                          }
                          let data = {
                            id:'',
                            idNo:$this.idNo,
                            itemNo: maxNo+1,
                            programName: item.programName,
                            masterPrice: item.price,
                            materialNo: item.materialNo,
                            materialName: item.materialName,
                            materialType: item.specification,//规格
                            barCode: item.barCode,
                            materialDesc: item.remark,
                            unit:'PCS',
                            price:item.price,
                            customPrice: item.price,
                            deliDate:dateFormat(deliDate,"yyyy-MM-dd"),
                            prodNum:0,
                            prodComplete:isComplete?'是':'否',
                            stockNum:0,
                            stockComplete:isComplete?'是':'否',
                            deliNum:0,
                            deliComplete:isComplete?'是':'否',
                            totalStockNum:0,
                            pcsCount:0,
                            cubeNum:0,
                            maxNum:item.maxNum,
                            abc: item.abc,
                            fullBox: item.fullBox,
                            packSize: item.packSize,
                            packLabelName:"标准箱唛",
                              packLabelContent:item.packLabel,
                            packLabel2:item.packLabel2,
                            packLabel3:item.packLabel3
                          }
                          // const obj = $table.insertAt(data, -1);
                          $this.$refs.tableRef.insertAt(data, -1);
                          // console.log(obj)
                          // }
                        })
                    }
                }
            },
            contextMenuClickEvent(data) {
                const menu = data.menu;
                const row = data.row;
                const column = data.column;
                const $table = this.$refs.tableRef
                if ($table) {
                    switch (menu.code) {
                        case 'hideColumn':
                            $table.hideColumn(column)
                            break
                        case 'showAllColumn':
                            $table.resetColumn(true)
                            break
                        case 'copy':
                            // if (XEClipboard.copy(row[column.field])) {
                            //   ElMessage.success('保存成功')
                            // }
                            // ElMessage.success('复制成功')
                            break
                        case 'reload':
                            //  findList()
                            break
                        case 'insertAt':
                            $table.insertAt({}, row || -1).then(({row}) => {
                                $table.setEditCell(row, column || 'name')
                            })
                            break
                        case 'remove':
                            $table.remove(row)
                            break
                        case 'save':
                            // ElMessage.success('保存成功')
                            break
                    }
                }
            },
            calcSum(list, field) {
                let count = 0
                list.forEach(item => {
                    count += Number(item[field])
                })
                if (field == 'totalPrice' || field == 'pcsCount' || field == 'cubeNum') {
                    return this.$toFixed(count,2);
                }else {
                    return this.$toFixed(count,0);
                }
            },
            // 在值发生改变时更新表尾合计
            updateFooterEvent (params) {
                let xTable = this.$refs.tableRef
                xTable.updateFooter()
            },
            footerMethod(table) {
                console.log("table",table);
                return [
                    table.columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计'
                        }
                        if (['num', 'totalPrice', 'prodNum', 'stockNum', 'deliNum', 'totalStockNum' , 'pcsCount', 'cubeNum'].includes(column.field)) {
                            return this.calcSum(table.data, column.field)
                        }
                        return null
                    })
                ]
            },
            disabledCommit(data) {
                this.$emit("disabledCommit",data);
            },
            editActivedEvent(row){//激活单元格事件
                this.disabledCommit(true);
            },
            editClosedEvent(row) {
                console.log(row)
                const $table = this.$refs.tableRef;
                $table.clearValidate();
                this.disabledCommit(false);
                // const $table = this.$refs.tableRef
                // console.log($table.getTableData().fullData);
                // const err = this.validEvent(row.row);
                // if (err) {
                //     return
                // }
                // if (row.column.field=='num') {
                //     this.changeAbc(row.row.num, row.row);
                // }
            },
            handleSaveRow(row) {
                const err = this.validEvent(row);
                if (err) {
                    return
                }

            },
            async validEvent(row) {
                const $table = this.$refs.tableRef
                const errMap = await $table.validate(row).catch(errMap => errMap)
                return errMap;

            },
            setData(editable,idNo) {
                // if (list)
                //     this.list = list;

                if(idNo){
                    this.query.idNo = idNo
                    this.idNo = idNo
                }
                console.log("aaaaaa", this.idNo)
                // this.customerId = customerId
                this.onLoad(this.page)

                this.editable = editable;
                console.log(this.editable);
            },
            formatType(value) {
                let value2 = "";
                this.customerTypeList.forEach(res => {
                    if (value === res.dictKey) {
                        value2 = res.dictValue;
                    }
                });
                return value2
            },
            initDict() {
                getDictionary({code: 'biz_yes_no'}).then(res => {
                    this.yesNoList = res.data.data;
                });
                unitSelect().then(res => {
                    this.unitList = res.data.data;
                });
            },
            // 主表模块
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            async handleDelete(row) {
                const $table = this.$refs.tableRef
                if (row.id) {
                    this.$confirm('是否确认删除?', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        checkProd(row.id).then(res => {
                            if (res.data.success) {
                                if ($table.getTableData().fullData.length === 1) {
                                  this.$emit("disabledFiled", false);
                                }
                                $table.remove(row)
                                this.$message({type: "success", message: "操作成功，保存后生效!"});
                            } else {
                                this.$message({type: "error", message: res.data.msg || "该订单项已排产，不允许删除！"});
                            }
                        })
                    })
                } else {
                    if ($table.getTableData().fullData.length === 1) {
                      this.$emit("disabledFiled", false);
                    }
                    $table.remove(row)
                }
            },
            // handleDelete() {
            //   if (this.selectionList.length === 0) {
            //     this.$message.warning("请选择至少一条数据");
            //     return;
            //   }
            //   this.$confirm("确定将选择数据删除?", {
            //     confirmButtonText: "确定",
            //     cancelButtonText: "取消",
            //     type: "warning"
            //   })
            //     .then(() => {
            //       return remove(this.ids);
            //     })
            //     .then(() => {
            //       this.onLoad(this.page);
            //       this.$message({
            //         type: "success",
            //         message: "操作成功!"
            //       });
            //       this.$refs.crud.toggleSelection();
            //     });
            // },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                if(this.$refs.crud)  this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            onLoad(page, params = {}) {
                if (this.$refs.tableRef.getInsertRecords().length>0 || this.$refs.tableRef.getRemoveRecords().length>0 ||
                    this.$refs.tableRef.getUpdateRecords().length>0) {
                    this.$confirm("搜索会丢失本次新增/编辑/删除的数据，确定继续吗?", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    })
                        .then(() => {
                            this.loading = true;
                            console.log('aaaaaaaaaaaa', this.query)
                            // this.query.idNo = this.idNo;
                            findList(Object.assign(params, this.query)).then(res => {
                                const data = res.data.data;
                                // this.page.total = data.total;
                                this.calcLoadData(data);
                                this.list = data;
                                this.loading = false;
                                this.selectionClear();
                            });
                        })
                }else {
                    this.loading = true;
                    console.log('aaaaaaaaaaaa', this.query)
                    // this.query.idNo = this.idNo;
                    findList(Object.assign(params, this.query)).then(res => {
                        const data = res.data.data;
                        // this.page.total = data.total;
                        this.calcLoadData(data);
                        this.list = data;
                        this.loading = false;
                        this.selectionClear();
                    });
                }
            },

            calcLoadData(data) {
                data.forEach(row => {
                    if (row.num && row.price) {
                        row.totalPrice = this.$toFixed(row.price/100*row.num,2);
                    }
                    if (row.maxNum && row.maxNum> 0) {
                        row.pcsCount = Math.ceil(this.$toFixed(row.num/row.maxNum,3));
                        console.log(row.pscCount);
                        if (row.packSize ) {
                            row.cubeNum = this.$toFixed(Math.ceil(row.num/row.maxNum) * row.packSize,2);
                        }
                    }
                })
            }

        }
    };
</script>

<style scoped>
  .overhidden{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    height:50px;
  }
</style>
